/*
Copyright 2009 Lawren Quigley-Jones

   trade-assistant.js is part of Preopoly.

   Preopoly is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Preopoly is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Preopoly.  If not, see <http://www.gnu.org/licenses/>.

   Contact Lawren Quigley-Jones with questions or bugs:
   lawrenqj@gmail.com
*/

function TradeAssistant() {
	/* this is the creator function for your scene assistant object. It will be passed all the 
	   additional parameters (after the scene name) that were passed to pushScene. The reference
	   to the scene controller (this.controller) has not be established yet, so any initialization
	   that needs the scene controller should be done in the setup function below. */
}

TradeAssistant.prototype.setup = function() {
try {
  this.requestPlayer = -1;
  //this.requestProperty = -1;

		// negotiate and print offer player
  this.offerPlayer = curPlayer;
  this.controller.get('OfferPlayer').update(playerArray[this.offerPlayer].playerName + ' ($' + playerArray[this.offerPlayer].money + ')');

		// offer property list
  this.controller.setupWidget('OfferPropertyList', 
    {
      itemTemplate: 'trade/propertyItem',
      swipeToDelete: true,
      autoconfirmDelete: true,
      deletedProperty: 'swiped',
    },
    this.offerPropertyListModel = {
      items: []
    }
  );
  this.controller.listen('OfferPropertyList', Mojo.Event.listDelete, this.offerPropertyDelete.bindAsEventListener(this));

              // offer property selector
  this.offerPropertyList = [];
  this.offerPropertyAll = listOwnedProperties(this.offerPlayer);

  var offerProperties = this.genPropertySelector(this.offerPropertyAll, this.offerPropertyList);

  this.controller.setupWidget('OfferProperty',
    {
    label: 'property',
    choices: offerProperties,
    modelProperty: 'selected'
    },
    this.offerPropertySelectorModel = {
    }
  ); 
  //this.controller.listen('OfferProperty', Mojo.Event.propertyChange, this.offerPropertyUpdate.bindAsEventListener(this));
  Mojo.Event.listen(this.controller.get('OfferProperty'), Mojo.Event.propertyChange, this.offerPropertyUpdate.bindAsEventListener(this));

              // player selector
  var otherPlayers = this.genOtherPlayers();
  this.controller.setupWidget('RequestPlayer',
    {
    label: 'player',
    choices: otherPlayers,
    modelProperty: 'selectedPlayer'
    },
    this.requestPlayerSelectorModel = {}
  ); 
  Mojo.Event.listen(this.controller.get('RequestPlayer'), Mojo.Event.propertyChange, this.requestPlayerUpdate.bindAsEventListener(this));

		// request property list
  this.controller.setupWidget('RequestPropertyList', 
    {
      itemTemplate: 'trade/propertyItem',
      swipeToDelete: true,
      autoconfirmDelete: true,
      deletedProperty: 'swiped',
    },
    this.requestPropertyListModel = {
      items: []
    }
  );
  this.controller.listen('RequestPropertyList', Mojo.Event.listDelete, this.requestPropertyDelete.bindAsEventListener(this));

              // request property selector
  this.requestPropertyList = [];
  this.requestPropertyAll = []
  for ( var i=0; i<propertyOwner.length; i++ ) {
    if ( propertyOwner[i].owner == null ) continue;
    if ( propertyOwner[i].owner != curPlayer ) this.requestPropertyAll.push(i);
  }

  var requestProperties = this.genPropertySelector(this.requestPropertyAll, this.requestPropertyList);
  this.controller.setupWidget('RequestProperty',
    {
    label: 'property',
    choices: requestProperties,
    modelProperty: 'selected'
    },
    this.requestPropertySelectorModel = {}
  ); 
  Mojo.Event.listen(this.controller.get('RequestProperty'), Mojo.Event.propertyChange, this.requestPropertyUpdate.bindAsEventListener(this));

		// offer money
  this.controller.get("OfferMoneyText").update('$0');
  this.offerMoneyModel = {
    value: 0,
    disabled: false
  };
  this.controller.setupWidget("OfferMoneyID", {
      modelProperty: 'value',
      minValue: 0,
      maxValue: 1,
      round: false,
      updateInterval: 0.5
    },
    this.offerMoneyModel);
  Mojo.Event.listen(this.controller.get('OfferMoneyID'), Mojo.Event.propertyChange, this.offerMoneyUpdate.bindAsEventListener(this));

		// request money
  this.controller.get("RequestMoneyText").update('$0');
  
  this.controller.setupWidget("RequestMoneyID", 
    {
      modelProperty: 'value',
      minValue: 0,
      maxValue: 1,
      round: false,
      updateInterval: 0.5
    },
    this.requestMoneyModel = {
      value: 0,
      disabled: false
    });
  Mojo.Event.listen(this.controller.get('RequestMoneyID'), Mojo.Event.propertyChange, this.requestMoneyUpdate.bindAsEventListener(this));

                // submit button
  this.submitButtonModel = {
    buttonLabel : 'Offer Deal to Player',
    buttonClass : '',
    disable : false
  };
  this.controller.setupWidget('SubmitOfferID', {}, this.submitButtonModel);
  Mojo.Event.listen(this.controller.get('SubmitOfferID'), Mojo.Event.tap, this.offerSubmit.bind(this));
} catch(x) { if ( debug ) Mojo.Log.error('Exception in trade setup: ' + x); }
}

TradeAssistant.prototype.genOtherPlayers = function() {
  var otherPlayers = [];
  //for ( var i=0; i<numPlayers; i++ ) {
  //  if ( i == curPlayer ) continue;
  //  if ( playerArray[i].bankrupt ) continue;
  //  otherPlayers.push({ label: playerArray[i].playerName + ' ($' + playerArray[i].money + ')', value: i });
  //}
  for ( var i=0; i<playerList.length; i++ ) {
    if ( playerList[i] == curPlayer || playerArray[playerList[i]].bankrupt ) continue;
    otherPlayers.push({
      label: playerArray[playerList[i]].playerName + ' ($' + playerArray[playerList[i]].money + ')',
      value: playerList[i]
      });
  }

  return otherPlayers;
}

TradeAssistant.prototype.offerPropertyDelete = function(event) {
  this.offerPropertyList = this.removeProp(this.offerPropertyList, event.item.propertyNum);
		// update property selector...
  this.offerPropertySelectorModel.choices = this.genPropertySelector(this.offerPropertyAll, this.offerPropertyList);
  this.offerPropertySelectorModel.selected = undefined;
  this.controller.modelChanged(this.offerPropertySelectorModel, this);
}

TradeAssistant.prototype.requestPropertyDelete = function(event) {
  this.requestPropertyList = this.removeProp(this.requestPropertyList, event.item.propertyNum);
		// update property selector...
  this.requestPropertySelectorModel.choices = this.genPropertySelector(this.requestPropertyAll, this.requestPropertyList);
  this.requestPropertySelectorModel.selected = undefined;
  this.controller.modelChanged(this.requestPropertySelectorModel, this);
}

TradeAssistant.prototype.removeProp = function(propArray, prop) {
try {
  var tmpA = [];
  found = 0;
  for ( var i=0; i<propArray.length; i++ ) {
    if ( propArray[i] == prop ) 
      found = 1;
    else
      tmpA.push(propArray[i]);
  }
  return tmpA
} catch(x) { if ( debug ) Mojo.Log.error('Exception in remove prop: ' + x); }
}

//TradeAssistant.prototype.updatePropertyList = function(propArray, listID) {
//  var list = "";
//  for ( var i = 0; i<propArray.length; i++ )
//    list += propertyArray[ propArray[i] ][propertyName] + "<br>";
//  this.controller.get(listID).update(list);
//}

TradeAssistant.prototype.genPropertySelector = function(propall, propselected) {
  var ret = [];
  for ( var i=0; i<propall.length; i++ ) {

    var found = 0;
    for ( var j=0; j<propselected.length; j++ )
      if ( propall[i] == propselected[j] ) found = 1;

    if ( found ) continue;

    ret.push({
      label: propertyArray[ propall[i] ][propertyName],
      value: propall[i]
    });
  }
  return ret;
}

TradeAssistant.prototype.offerPropertyUpdate = function(event) {
try {
  this.offerPropertyList.push(this.offerPropertySelectorModel.selected);
  var tmp = [];
  for ( var i=0; i<this.offerPropertyList.length; i++) {
    tmp.push({
      propertyColor: propertyArray[this.offerPropertyList[i]][propertyColor],
      propertyName: propertyArray[this.offerPropertyList[i]][propertyName],
      propertyNum: this.offerPropertyList[i]
    })
  }
  this.offerPropertyListModel.items = tmp;
  this.controller.modelChanged(this.offerPropertyListModel, this);
		// update property selector
  this.offerPropertySelectorModel.choices = this.genPropertySelector(this.offerPropertyAll, this.offerPropertyList);
  this.offerPropertySelectorModel.selected = undefined;
  this.controller.modelChanged(this.offerPropertySelectorModel, this);
} catch(x) { if ( debug ) Mojo.Log.error('Exception in offer property update: ' + x); }
}

TradeAssistant.prototype.requestPropertyUpdate = function(event) {
  this.requestPropertyList.push(this.requestPropertySelectorModel.selected);
  var tmp = [];
  for ( var i=0; i<this.requestPropertyList.length; i++) {
    tmp.push({
      propertyColor: propertyArray[this.requestPropertyList[i]][propertyColor],
      propertyName: propertyArray[this.requestPropertyList[i]][propertyName],
      propertyNum: this.requestPropertyList[i]
    })
  }
  this.requestPropertyListModel.items = tmp;
  this.controller.modelChanged(this.requestPropertyListModel, this);

		// if user has not yet selected a player...
  if ( this.requestPlayerSelectorModel.selectedPlayer == undefined ) {
		// update the request player
    if ( this.requestPropertySelectorModel.selected == undefined ) return 0;
    this.requestPlayer = propertyOwner[ this.requestPropertySelectorModel.selected ].owner;
    this.requestPlayerSelectorModel.selectedPlayer = this.requestPlayer;
    this.controller.modelChanged(this.requestPlayerSelectorModel, this);
		// update requestPropertyAll
    this.requestPropertyAll = listOwnedProperties(this.requestPlayer);
  }
		// update property selector
  this.requestPropertySelectorModel.choices = this.genPropertySelector(this.requestPropertyAll, this.requestPropertyList);
  this.requestPropertySelectorModel.selected = undefined;
  this.controller.modelChanged(this.requestPropertySelectorModel, this);
}

TradeAssistant.prototype.requestPlayerUpdate = function(event) {
try {
  this.requestPlayer = this.requestPlayerSelectorModel.selectedPlayer;

		// clear the request property list
  this.requestPropertyList = [];
  this.requestPropertyListModel.items = this.requestPropertyList;
  this.controller.modelChanged(this.requestPropertyListModel, this);

		// get and format request property list
  this.requestPropertyAll = listOwnedProperties(this.requestPlayer);
  this.requestPropertySelectorModel.choices = this.genPropertySelector(this.requestPropertyAll, this.requestPropertyList);
  this.requestPropertySelectorModel.selected = undefined;
  this.controller.modelChanged(this.requestPropertySelectorModel, this);

		//changing maxValue doesn't work....
  this.requestMoneyModel.value = 0;
  this.controller.modelChanged(this.requestMoneyModel, this);
  this.controller.get("RequestMoneyText").update('$0');

} catch(x) { if ( debug ) Mojo.Log.error('Exception in request player update: ' + x); }
}

TradeAssistant.prototype.offerMoneyUpdate = function(event) {
  this.controller.get("OfferMoneyText").update( '$' + this.offerMoney() );
}

TradeAssistant.prototype.offerMoney = function() {
  var money = this.offerMoneyModel.value * playerArray[this.offerPlayer].money;
  return Math.round(money);
}

TradeAssistant.prototype.requestMoney = function() {
  //var money = this.requestMoneyModel.value * playerArray[this.requestPlayer].money;
  var money = this.requestMoneyModel.value * ( playerArray[this.requestPlayer].money + getMortgageableAssets(this.requestPlayer) );
  return Math.round(money);
}

TradeAssistant.prototype.requestMoneyUpdate = function(event) {
  this.controller.get("RequestMoneyText").update( '$' + this.requestMoney() );
}

TradeAssistant.prototype.popup = function(text) {
  this.controller.showAlertDialog({
    onChoose: function(value) {},
    title: $L( text ),
    choices:[ {label:$L("OK"), value:""} ]
  });       
}
TradeAssistant.prototype.offerSubmit = function(event) {
try {
  if ( this.requestPlayer < 0 ) {
    this.controller.showAlertDialog({
      onChoose: function(value) {},
      title: $L( "Select a player to trade with" ),
      choices:[ {label:$L("OK"), value:""} ]
    });       
    return 1;
  }
  else if ( ! isComputer(this.requestPlayer) ) {
    //if ( this.requestMoneyModel.value > playerArray[this.requestPlayer].money ) {
    if ( this.requestMoney() > playerArray[this.requestPlayer].money ) {
      this.controller.showAlertDialog({
        onChoose: function(value) {},
        title: $L( playerArray[this.offerPlayer].playerName + " doesn't have that much money" ),
        choices:[ {label:$L("OK"), value:""} ]
      });       
      return 1;
    }
    var offerHash = {
      money: this.offerMoney(),
      player: this.offerPlayer,
      properties: this.offerPropertyList
    };
    var requestHash = {
      //money: this.requestMoneyModel.value,
      money: this.requestMoney(),
      player: this.requestPlayer,
      properties: this.requestPropertyList
    };
    var offerText = tradeText(offerHash, requestHash);

    this.controller.showAlertDialog({
      onChoose: function(value) {
        performTrade(offerHash, requestHash);
        this.clearForm();
        saveDynamicObjects();
      },
      title: $L( playerArray[this.offerPlayer].playerName + " offers you a trade" ),
      message: $L(offerText),
      choices:[ {label:$L("Accept"), value:"accept"}, {label:$L("Reject"), value:"reject"} ]
    });       
    return 1;
  }
  else {
    var offerValue = this.offerMoney();
    if ( offerValue == undefined ) offerValue = 0;
    //var requestValue = this.requestMoneyModel.value;
    var requestValue = this.requestMoney();
    if ( requestValue == undefined ) requestValue = 0;
  
    for ( var i=0; i<this.offerPropertyList.length; i++ ) {
      offerValue += propertyTradeValue(this.offerPropertyList[i], this.requestPlayer);
    }
    for ( var i=0; i<this.requestPropertyList.length; i++ ) {
      if ( isMonopoly(this.requestPropertyList[i], this.requestPlayer) ) {
        this.popup("That's a monopoly.  I'm not giving it up.");
        return 1;
      }
      requestValue += propertyTradeValue(this.requestPropertyList[i], this.offerPlayer);
    }
  
    //if ( debug ) Mojo.Log.error("offer: " + offerValue + ", request: " + requestValue);
  
  		// compare the values
    if ( offerValue == 0 ) {
      this.popup("You've got to give me something");
      return 1;
    }
    else if ( requestValue == 0 ) {
      this.popup("You're never going to win if give stuff away");
      return 1;
    }
    else if ( offerValue > requestValue ) {
      if ( this.offerMoney() > playerArray[this.offerPlayer].money ) {
        this.popup("You don't have that much money");
        return 1;
      }
      //else if ( this.requestMoneyModel.value > ( playerArray[this.requestPlayer].money + getMortgageableAssets(this.requestPlayer) ) ) {
      else if ( this.requestMoney() > ( playerArray[this.requestPlayer].money + getMortgageableAssets(this.requestPlayer) ) ) {
        this.popup("I don't have that much money");
        return 1;
      }
      else {
        //if ( this.requestMoneyModel.value > playerArray[this.requestPlayer].money ) {
        if ( this.requestMoney() > playerArray[this.requestPlayer].money ) {
          //if ( ! autoMortgage(this.requestPlayer, this.requestMoneyModel.value ) ) {
          if ( ! autoMortgage(this.requestPlayer, this.requestMoney() ) ) {
            this.popup("I couldn't raise that much money.");
            return 1;
          }
        }
        var offerHash = { money: this.offerMoney(), player: this.offerPlayer, properties: this.offerPropertyList };
        //var requestHash = { money: this.requestMoneyModel.value, player: this.requestPlayer, properties: this.requestPropertyList };
        var requestHash = { money: this.requestMoney(), player: this.requestPlayer, properties: this.requestPropertyList };
        if ( performTrade(offerHash, requestHash) ) {
          this.popup("done!");
          this.clearForm();
          saveDynamicObjects();
          this.controller.get('OfferPlayer').update(playerArray[this.offerPlayer].playerName + ' ($' + playerArray[this.offerPlayer].money + ')');
          this.requestPlayerSelectorModel.choices = this.genOtherPlayers();
          this.controller.modelChanged(this.requestPlayerSelectorModel, this);
        }
        else {
          this.popup("Something went wrong");
        }
      }
    }
    else if ( ( offerValue + 300 ) > requestValue ) {
      this.popup("Just a little more...");
    }
    else if ( ( offerValue * 1.5 ) > requestValue ) {
      this.popup("I don't think so...");
    }
    else {
      this.popup("Not even close!");
    }
  }
} catch(x) { if ( debug ) Mojo.Log.error('Exception in offer submit: ' + x); }
}

TradeAssistant.prototype.clearForm = function() {
try {
  		// clear and format offer property selector
        this.offerPropertySelectorModel.choices = this.genPropertySelector(listOwnedProperties(this.offerPlayer), []);
        this.offerPropertySelectorModel.selected = undefined;
        this.controller.modelChanged(this.offerPropertySelectorModel, this);
		// reset property list
        this.offerPropertyList = [];
        this.offerPropertyListModel.items = this.offerPropertyList;
        this.controller.modelChanged(this.offerPropertyListModel, this);
  		// reset offer money
        this.offerMoneyModel.value = 0;
        this.controller.modelChanged(this.offerMoneyModel, this);
        this.controller.get("OfferMoneyText").update('$0');
  		// clear and format request property selector
        this.requestPropertySelectorModel.choices = this.genPropertySelector(listOwnedProperties(this.requestPlayer), []);
        this.requestPropertySelectorModel.selected = undefined;
        this.controller.modelChanged(this.requestPropertySelectorModel, this);
		// reset property list
        this.requestPropertyList = [];
        this.requestPropertyListModel.items = this.requestPropertyList;
        this.controller.modelChanged(this.requestPropertyListModel, this);
  		// reset request money
        this.requestMoneyModel.value = 0;
        this.controller.modelChanged(this.requestMoneyModel, this);
        this.controller.get("RequestMoneyText").update('$0');
} catch(x) { if ( debug ) Mojo.Log.error('Exception in clear form: ' + x); }
}

TradeAssistant.prototype.activate = function(event) {
	/* put in event handlers here that should only be in effect when this scene is active. For
	   example, key handlers that are observing the document */
}


TradeAssistant.prototype.deactivate = function(event) {
	/* remove any event handlers you added in activate and do any other cleanup that should happen before
	   this scene is popped or another scene is pushed on top */
}

TradeAssistant.prototype.cleanup = function(event) {
	/* this function should do any cleanup needed before the scene is destroyed as 
	   a result of being popped off the scene stack */
  Mojo.Event.stopListening(this.controller.get('RequestProperty'), Mojo.Event.propertyChange, this.requestPropertyUpdate.bindAsEventListener(this));
  Mojo.Event.stopListening(this.controller.get('OfferProperty'), Mojo.Event.propertyChange, this.offerPropertyUpdate.bindAsEventListener(this));
  Mojo.Event.stopListening(this.controller.get('RequestPlayer'), Mojo.Event.propertyChange, this.requestPlayerUpdate.bindAsEventListener(this));
  Mojo.Event.stopListening(this.controller.get('OfferMoneyID'), Mojo.Event.propertyChange, this.offerMoneyUpdate.bindAsEventListener(this));
  Mojo.Event.stopListening(this.controller.get('RequestMoneyID'), Mojo.Event.propertyChange, this.requestMoneyUpdate.bindAsEventListener(this));
  Mojo.Event.stopListening(this.controller.get('SubmitOfferID'), Mojo.Event.tap, this.offerSubmit.bind(this));
}
